package mn.idax.exchange.otc.task;

import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.elasticjob.lite.annotation.ElasticSimpleJob;
import mn.idax.exchange.otc.config.AdProducter;
import mn.idax.exchange.otc.entity.OTCAds;
import mn.idax.exchange.otc.enums.AdEnum;
import mn.idax.exchange.otc.enums.MessageNotifyEnum;
import mn.idax.exchange.otc.service.OTCAdsService;
import mn.idax.exchange.otc.util.DateUtils;
import mn.idax.exchange.otc.util.LogUtils;
import mn.idax.exchange.otc.util.MessageNotifyUtils;
import mn.idax.exchange.otc.vo.OTCAutoDownAdDTO;
import mn.idax.exchange.otc.vo.SyncAdInMemory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: dison
 * @Date: 2018/9/28 14:02
 * @Description:定时任务更新广告过期
 */
@ElasticSimpleJob(cron = "0 0/1 * * * ?")
@Component
public class AdvertisingExpireJob implements SimpleJob {

    @Autowired
    private OTCAdsService otcAdsService;

    @Autowired
    private AdProducter adProducter;

    @Override
    public void execute(ShardingContext shardingContext) {

        Date currDate = DateUtils.getUTCNow();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("expirestate", AdEnum.state_expire.getCode());
        map.put("upstate", AdEnum.state_up.getCode());
        map.put("currdate", currDate);

        int total = 0;
        //方式一：先查出过期的数据，然后循环单笔更新
        List<OTCAds> list = otcAdsService.getExpireBatchOTCAdsState(map);
        if (!list.isEmpty()) {
            for (OTCAds otcAds : list) {
                OTCAutoDownAdDTO otcAutoDownAdDTO = new OTCAutoDownAdDTO();
                otcAutoDownAdDTO.setUpdateTime(currDate);
                otcAutoDownAdDTO.setState(AdEnum.state_expire.getCode());
                otcAutoDownAdDTO.setId(otcAds.getId());
                int count = otcAdsService.updateStateOTCAdsById(otcAutoDownAdDTO);
                if (count == 1) {
                    //将广告从内存中移除
                    adProducter.sendDownAdMessage(JSON.toJSONString(new SyncAdInMemory(otcAds.getId(),otcAds.getPublisherid())));
                    LogUtils.info(this.getClass(), "AdvertisingJobExpireAd adId : " + otcAds.getId());
                    total++;
                    // 发送我的通知消息
                    MessageNotifyUtils.sendNotify(otcAds.getPublisherid(),
                            otcAds.getId(),
                            MessageNotifyEnum.BodyTemplate.ad_expire_cancel);
                }

            }
        }

        //方式二：一行sql批量更新
//    	total = otcAdsService.expireBatchOTCAdsState(map);

        LogUtils.info(this.getClass(), "AdvertisingExpireJob run finish,influence ads:" + total);
    }
}
